/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.common.util;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.media.Schema;
// import org.apache.commons.lang3.StringUtils;
import org.springdoc.core.annotations.ParameterObject;

// import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 增强分页参数类（包含HTML生成能力）
 * @author lanhai
 */
@Schema
@ParameterObject
public class PageParam<T> extends Page<T> {
    private static final int DEFAULT_PAGE_RANGE = 5;
    private static final int MAX_PAGE_SIZE = 100;

    /**
     * 每页显示条数，默认 10
     */
    @Schema(description = "每页大小，默认10")
    private long size = 10;

    /**
     * 当前页
     */
    @Schema(description = "当前页，默认1")
    private long current = 1;

    /**
     * 查询数据列表
     */
    @Hidden
    private List<T> records;
    
    /**
     * 总数
     */
    @Hidden
    private long total = 0;

    /**
     * 是否进行 count 查询
     */
    @JsonIgnore
    private boolean isSearchCount = true;

    @JsonIgnore
    private String countId;
    @JsonIgnore
    private Long maxLimit;
    @JsonIgnore
    private boolean optimizeCountSql;

    /* ----------- 原有方法保持不变 ----------- */
    @Override
    public List<T> getRecords() {
        return this.records;
    }

    @Override
    public Page<T> setRecords(List<T> records) {
        this.records = records;
        return this;
    }

    @Override
    public long getTotal() {
        return this.total;
    }

    @Override
    public Page<T> setTotal(long total) {
        this.total = total;
        return this;
    }

    @JsonIgnore
    public boolean getSearchCount() {
        if (total < 0) {
            return false;
        }
        return isSearchCount;
    }

    @Override
    public Page<T> setSearchCount(boolean isSearchCount) {
        this.isSearchCount = isSearchCount;
        return this;
    }

    @Override
    public long getSize() {
        return this.size;
    }

    @Override
    public Page<T> setSize(long size) {
        this.size = Math.min(size, MAX_PAGE_SIZE);
        return this;
    }

    @Override
    public long getCurrent() {
        return this.current;
    }

    @Override
    public Page<T> setCurrent(long current) {
        this.current = current;
        return this;
    }

    /* ----------- 新增HTML生成方法 ----------- */
    
    /**
     * 生成分页HTML（自动从HttpRequest获取URL）
     */
    // public String generatePaginationHtml(HttpServletRequest request) {
    //     String url = request.getRequestURL().toString();
    //     String queryString = request.getQueryString();
    //     String fullUrl = url + (StringUtils.isNotEmpty(queryString) ? "?" + queryString : "");
    //     return generatePaginationHtml(fullUrl);
    // }

    /**
     * 生成分页HTML
     * @param baseUrl 基础URL（自动处理参数）
     */
    public String generatePaginationHtml(String baseUrl) {  //这个方法用不上。

        // 使用示例：
        /*@GetMapping("/page")
        public ServerResponseEntity<PageParam<Book>> getPage(PageParam<Book> pageParam, 
                                                             HttpServletRequest request) {
            PageParam<Book> page = bookService.page(pageParam);
            
            // 直接通过分页对象生成HTML
            String paginationHtml = page.generatePaginationHtml(request);
            
            return ServerResponseEntity.success(page)
                    .addData("paginationHtml", paginationHtml);
        }*/


        // 参数校验
        if (this.getSize() <= 0) {
            return "";
        }

        long totalPages = (this.getTotal() + this.getSize() - 1) / this.getSize();
        if (totalPages <= 1) {
            return "";
        }

        // 构建URL
        String url = baseUrl.contains("?") ? baseUrl + "&" : baseUrl + "?";
        url = url.replaceAll("([&?])p=\\d+", "$1").replaceAll("&$", "");

        StringBuilder html = new StringBuilder()
            .append("<div class=\"pagination-container\">")
            .append("<div class=\"pagination\">");

        // 上一页
        if (this.getCurrent() > 1) {
            html.append(buildPageLink("prev", "上一页", url, this.getCurrent() - 1));
        }

        // 页码按钮
        long start = Math.max(1, this.getCurrent() - DEFAULT_PAGE_RANGE / 2);
        long end = Math.min(totalPages, start + DEFAULT_PAGE_RANGE - 1);

        if (end - start + 1 < DEFAULT_PAGE_RANGE) {
            start = Math.max(1, end - DEFAULT_PAGE_RANGE + 1);
        }

        // 首页
        if (start > 1) {
            html.append(buildPageLink("first", "1", url, 1));
            if (start > 2) html.append("<span class=\"ellipsis\">...</span>");
        }

        // 页码
        for (long i = start; i <= end; i++) {
            html.append(i == this.getCurrent() ? 
                buildCurrentPage(i) : 
                buildPageLink("num", String.valueOf(i), url, i));
        }

        // 尾页
        if (end < totalPages) {
            if (end < totalPages - 1) html.append("<span class=\"ellipsis\">...</span>");
            html.append(buildPageLink("last", String.valueOf(totalPages), url, totalPages));
        }

        // 下一页
        if (this.getCurrent() < totalPages) {
            html.append(buildPageLink("next", "下一页", url, this.getCurrent() + 1));
        }

        return html.append("</div></div>").toString();
    }

    private String buildPageLink(String cls, String text, String url, long page) {
        return String.format("<a class=\"%s\" href=\"%sp=%d\">%s</a>", cls, url, page, text);
    }

    private String buildCurrentPage(long page) {
        return String.format("<span class=\"current\">%d</span>", page);
    }
}